import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
import "./index.css";
import { UploadOutlined, UserOutlined } from "@ant-design/icons";
import { Menu, Layout } from "antd";
import { useNavigate } from "react-router-dom";
const { Sider } = Layout;

const createMenuItem = (key, icon, label, children = "") => ({
  key,
  icon,
  label,
  children,
});
const iconMap = {
  "/home": <UploadOutlined />,
  "/right-manage": <UploadOutlined />,
  "/user-manage": <UserOutlined />,
  "/news-manage": <UploadOutlined />,
  "/audit-manage": <UploadOutlined />,
  "/publish-manage": <UploadOutlined />,
};
const SideMenu = (props) => {
  const [menu, setMenu] = useState();
  const [collapsed] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const { pathname: selectedKey } = useLocation();
  const openKeys = "/" + selectedKey.split("/")[1];
  let navigate = useNavigate();
  useEffect(() => {
    const fetchMenuData = async () => {
      try {
        const apiUrl = process.env.REACT_APP_API_URL + "/rights";
        const response = await fetch(apiUrl);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        setMenu(data);
        setIsLoading(false);
      } catch (error) {
        console.error("Fetching menu data failed:", error.message);
        setIsLoading(false);
      }
    };
    fetchMenuData();
  }, []);
  const handleClick = (e) => {
    navigate(e.key);
  };

  const roleItem = localStorage.getItem("token");
  const {
    role: { rights },
  } = JSON.parse(roleItem);
  const checkPagePermission = (menu) => {
    return (
      menu.pagepermisson &&
      (Array.isArray(rights)
        ? rights.includes(menu.key)
        : rights.checked.includes(menu.key))
    );
  };
  // 优化菜单数据的处理方式，避免在每次渲染时都重新计算
  const menuData = (menu) => {
    if (!menu) return [];
    return menu.map((item) => {
      if (
        item.children &&
        item.children.length !== 0 &&
        checkPagePermission(item)
      ) {
        return createMenuItem(
          item.key,
          iconMap[item.key],
          item.title,
          menuData(item.children),
        );
      } else {
        return (
          item.pagepermisson &&
          item.pagepermisson === 1 &&
          createMenuItem(item.key, iconMap[item.key], item.title)
        );
      }
    });
  };
  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
        <div className="login">新聞發佈系統</div>
        {isLoading ? (
          <div className="loading">Loading...</div>
        ) : (
          <div style={{ flex: 1, overflow: "auto" }}>
            <Menu
              theme="dark"
              mode="inline"
              selectedKeys={[selectedKey]}
              defaultOpenKeys={[openKeys]}
              onSelect={handleClick}
              items={menuData(menu)}
            ></Menu>
          </div>
        )}
      </div>
    </Sider>
  );
};

export default SideMenu;
